package com.cinnamon.rss.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cinnamon.rss.logic.RSSFeedParser;
import com.cinnamon.rss.model.Feed;
import com.cinnamon.rss.model.Item;
import com.cinnamon.rss.model.User;
import com.cinnamon.rss.repository.FeedRepository;
import com.cinnamon.rss.repository.ItemRepository;
import com.cinnamon.rss.repository.UserRepository;


/**
 * Handles requests for Feeds.
 */
@Controller
public class AndroidController {

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private FeedRepository feedRepository;

	@Autowired
	private ItemRepository itemRepository;
	
	/**
	 * Parse rss-xml from given URL and show the result of parsing
	*/
	@RequestMapping(value = "/{username}/{password}/addFeed", method = RequestMethod.POST)
	public void addFeed(@PathVariable("username") String username, @PathVariable("password") String password, @RequestParam("rss") String rss) {
		Md5PasswordEncoder encoder = new Md5PasswordEncoder();
		String hashedPassword = encoder.encodePassword(password, null);
		User user = userRepository.findByUsernameAndPassword(username, hashedPassword);	
		Feed feed = new RSSFeedParser(rss).readFeed();
		feed.setUser(user);
		feedRepository.save(feed);	
	}	

	/**
	 * Deletes a feed by id 
	 */
	@RequestMapping(value = "/{username}/{password}/feed/{id}/delete", method = RequestMethod.POST)		
	public void deleteFeed(@PathVariable("username") String username, 
			@PathVariable("password") String password, @PathVariable("id") long id) {	
		feedRepository.delete(id);		
	}
	
	/**
	 * Gets all user's feeds and send them an android client
	 * in a from of JSON.
	 */
	@RequestMapping(value = "/{username}/{password}/feeds", method = RequestMethod.GET, produces = {
			MediaType.APPLICATION_JSON_VALUE})
	@ResponseBody
	public List<Feed> getFeeds(@PathVariable("username") String username, @PathVariable("password") String password) {
		Md5PasswordEncoder encoder = new Md5PasswordEncoder();
		String hashedPassword = encoder.encodePassword(password, null);
		User user = userRepository.findByUsernameAndPassword(username, hashedPassword);	
		return feedRepository.findByUser(user);
	}
	
}
